<template>
  <!-- 切屏警告对话框 -->
  <el-dialog
    v-model="showWarningDialog"
    title="警告"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
  <!-- 11111 -->
    <div class="warning-content">
      <el-icon class="warning-icon"><WarningFilled /></el-icon>
      <p class="warning-text">检测到您切换了窗口或标签页！</p>
      <p class="warning-count">切屏次数：{{ switchCount }} 次</p>
      <p class="warning-tip">请立即返回考试页面，连续切屏可能导致考试被自动提交。</p>
    </div>
    <template #footer>
      <el-button type="primary" @click="handleConfirmWarning">确认已返回</el-button>
    </template>
  </el-dialog>
  
  <!-- 强制全屏提示 -->
  <el-dialog
    v-model="showFullscreenDialog"
    title="全屏提示"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div class="fullscreen-content">
      <p>为了确保考试公平，请在全屏模式下进行考试。</p>
      <p style="margin-top: 10px; color: #f56c6c;">点击下方按钮进入全屏模式。</p>
    </div>
    <template #footer>
      <el-button type="primary" @click="requestFullscreen">进入全屏</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { WarningFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { recordCheatingBehavior } from '../api/exam'

interface Props {
  examId: number
  maxSwitchCount?: number // 最大允许切屏次数，默认5次
}

const props = withDefaults(defineProps<Props>(), {
  maxSwitchCount: 5
})

const emit = defineEmits<{
  (e: 'exceedLimit'): void // 超过切屏次数限制
  (e: 'switchDetected', count: number): void // 检测到切屏
}>()

const showWarningDialog = ref(false)
const showFullscreenDialog = ref(false)
const switchCount = ref(0)
const isPageVisible = ref(true)
let lastSwitchTime = Date.now()

// 检测是否全屏
const checkFullscreen = () => {
  return !!(
    document.fullscreenElement ||
    (document as any).webkitFullscreenElement ||
    (document as any).mozFullScreenElement ||
    (document as any).msFullscreenElement
  )
}

// 请求全屏
const requestFullscreen = async () => {
  try {
    const element = document.documentElement
    if (element.requestFullscreen) {
      await element.requestFullscreen()
    } else if ((element as any).webkitRequestFullscreen) {
      await (element as any).webkitRequestFullscreen()
    } else if ((element as any).mozRequestFullScreen) {
      await (element as any).mozRequestFullScreen()
    } else if ((element as any).msRequestFullscreen) {
      await (element as any).msRequestFullscreen()
    }
    showFullscreenDialog.value = false
    ElMessage.success('已进入全屏模式')
  } catch (error) {
    ElMessage.error('全屏失败，请手动按F11进入全屏')
  }
}

// 检测页面可见性
const handleVisibilityChange = () => {
  const hidden = document.hidden || (document as any).webkitHidden || (document as any).mozHidden
  
  if (hidden) {
    // 页面不可见，检测到切屏
    isPageVisible.value = false
    const now = Date.now()
    
    // 防止频繁触发（至少间隔1秒）
    if (now - lastSwitchTime > 1000) {
      switchCount.value++
      lastSwitchTime = now
      
      // 记录作弊行为
      recordCheatingBehavior(props.examId, {
        type: 'switch_window',
        count: switchCount.value,
        timestamp: new Date().toISOString()
      }).catch(() => {
        // 静默失败，不影响考试流程
      })
      
      emit('switchDetected', switchCount.value)
      
      // 如果超过限制，触发事件
      if (switchCount.value >= props.maxSwitchCount) {
        emit('exceedLimit')
        ElMessage.error(`切屏次数已超过限制（${props.maxSwitchCount}次），考试将被提交！`)
      } else {
        // 显示警告对话框
        showWarningDialog.value = true
      }
    }
  } else {
    // 页面可见
    isPageVisible.value = true
  }
}

// 检测窗口焦点
const handleFocus = () => {
  if (!isPageVisible.value) {
    isPageVisible.value = true
  }
}

const handleBlur = () => {
  handleVisibilityChange()
}

// 检测全屏状态变化
const handleFullscreenChange = () => {
  if (!checkFullscreen()) {
    // 退出全屏，显示提示
    showFullscreenDialog.value = true
    ElMessage.warning('检测到退出全屏，请重新进入全屏模式')
  }
}

// 确认警告
const handleConfirmWarning = () => {
  showWarningDialog.value = false
}

// 禁止复制粘贴
const preventCopyPaste = (e: ClipboardEvent) => {
  e.preventDefault()
  e.stopPropagation()
  ElMessage.warning('考试期间禁止复制粘贴')
  return false
}

// 禁止右键菜单
const preventContextMenu = (e: MouseEvent) => {
  e.preventDefault()
  return false
}

// 禁止选择文本
const preventSelect = (e: MouseEvent) => {
  if ((e.target as HTMLElement).tagName !== 'INPUT' && 
      (e.target as HTMLElement).tagName !== 'TEXTAREA') {
    e.preventDefault()
    return false
  }
}

// 检测开发者工具
const detectDevTools = () => {
  let devtools = { open: false, orientation: null as any }
  const threshold = 160
  
  setInterval(() => {
    if ((window as any).outerHeight - window.innerHeight > threshold || 
        (window as any).outerWidth - window.innerWidth > threshold) {
      if (!devtools.open) {
        devtools.open = true
        ElMessage.error('检测到开发者工具，请关闭！')
        
        // 记录作弊行为
        recordCheatingBehavior(props.examId, {
          type: 'dev_tools',
          timestamp: new Date().toISOString()
        }).catch(() => {})
        
        // 可以选择自动提交考试
        // emit('exceedLimit')
      }
    } else {
      devtools.open = false
    }
  }, 500)
}

// 禁止快捷键
const preventShortcuts = (e: KeyboardEvent) => {
  // 禁止F12
  if (e.key === 'F12') {
    e.preventDefault()
    ElMessage.warning('考试期间禁止打开开发者工具')
    return false
  }
  
  // 禁止Ctrl+Shift+I (Chrome DevTools)
  if (e.ctrlKey && e.shiftKey && e.key === 'I') {
    e.preventDefault()
    ElMessage.warning('考试期间禁止打开开发者工具')
    return false
  }
  
  // 禁止Ctrl+Shift+C (Chrome DevTools)
  if (e.ctrlKey && e.shiftKey && e.key === 'C') {
    e.preventDefault()
    ElMessage.warning('考试期间禁止打开开发者工具')
    return false
  }
  
  // 禁止Ctrl+Shift+J (Chrome Console)
  if (e.ctrlKey && e.shiftKey && e.key === 'J') {
    e.preventDefault()
    ElMessage.warning('考试期间禁止打开开发者工具')
    return false
  }
  
  // 禁止Ctrl+U (查看源代码)
  if (e.ctrlKey && e.key === 'u') {
    e.preventDefault()
    ElMessage.warning('考试期间禁止查看源代码')
    return false
  }
  
  // 禁止Ctrl+S (保存网页)
  if (e.ctrlKey && e.key === 's') {
    e.preventDefault()
    ElMessage.warning('考试期间禁止保存网页')
    return false
  }
  
  // 禁止Ctrl+P (打印)
  if (e.ctrlKey && e.key === 'p') {
    e.preventDefault()
    ElMessage.warning('考试期间禁止打印')
    return false
  }
  
  // 禁止Ctrl+A (全选) - 但允许在输入框中使用
  if (e.ctrlKey && e.key === 'a') {
    const target = e.target as HTMLElement
    if (target.tagName !== 'INPUT' && target.tagName !== 'TEXTAREA') {
      e.preventDefault()
      ElMessage.warning('考试期间禁止全选')
      return false
    }
  }
}

onMounted(() => {
  // 检测页面可见性
  document.addEventListener('visibilitychange', handleVisibilityChange)
  window.addEventListener('focus', handleFocus)
  window.addEventListener('blur', handleBlur)
  
  // 检测全屏状态
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.addEventListener('mozfullscreenchange', handleFullscreenChange)
  document.addEventListener('MSFullscreenChange', handleFullscreenChange)
  
  // 禁止复制粘贴
  document.addEventListener('copy', preventCopyPaste)
  document.addEventListener('paste', preventCopyPaste)
  document.addEventListener('cut', preventCopyPaste)
  
  // 禁止右键菜单
  document.addEventListener('contextmenu', preventContextMenu)
  
  // 禁止选择文本（但允许在输入框中）
  document.addEventListener('selectstart', preventSelect as any)
  
  // 禁止快捷键
  document.addEventListener('keydown', preventShortcuts)
  
  // 检测开发者工具
  detectDevTools()
  
  // 检查是否全屏，如果不是则提示
  setTimeout(() => {
    if (!checkFullscreen()) {
      showFullscreenDialog.value = true
    }
  }, 1000)
})

onUnmounted(() => {
  // 移除所有事件监听
  document.removeEventListener('visibilitychange', handleVisibilityChange)
  window.removeEventListener('focus', handleFocus)
  window.removeEventListener('blur', handleBlur)
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.removeEventListener('mozfullscreenchange', handleFullscreenChange)
  document.removeEventListener('MSFullscreenChange', handleFullscreenChange)
  document.removeEventListener('copy', preventCopyPaste)
  document.removeEventListener('paste', preventCopyPaste)
  document.removeEventListener('cut', preventCopyPaste)
  document.removeEventListener('contextmenu', preventContextMenu)
  document.removeEventListener('selectstart', preventSelect as any)
  document.removeEventListener('keydown', preventShortcuts)
})
</script>

<style scoped>
.warning-content {
  text-align: center;
  padding: 20px 0;
}

.warning-icon {
  font-size: 48px;
  color: #f56c6c;
  margin-bottom: 15px;
}

.warning-text {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  margin: 10px 0;
}

.warning-count {
  font-size: 16px;
  color: #606266;
  margin: 10px 0;
}

.warning-tip {
  font-size: 14px;
  color: #909399;
  margin-top: 15px;
}

.fullscreen-content {
  padding: 20px 0;
  text-align: center;
}
</style>

